# ============================================================================
# PowerShell 版本兼容性检测
# ============================================================================

# 检测 PowerShell 版本并确保兼容性
function Test-PowerShellCompatibility {
    param(
        [Version]$MinimumVersion = "5.1.0",
        [Version]$RecommendedVersion = "7.0.0"
    )
    
    try {
        # 获取当前 PowerShell 版本
        $currentVersion = $PSVersionTable.PSVersion
        
        # 检查是否满足最低版本要求
        if ($currentVersion -lt $MinimumVersion) {
            Write-Host "❌ PowerShell 版本不兼容" -ForegroundColor Red
            Write-Host "   当前版本: $currentVersion" -ForegroundColor Yellow
            Write-Host "   最低要求: $MinimumVersion" -ForegroundColor Yellow
            Write-Host "   推荐版本: $RecommendedVersion" -ForegroundColor Green
            Write-Host ""
            Write-Host "请升级到 PowerShell $MinimumVersion 或更高版本后再使用此脚本。" -ForegroundColor Red
            Write-Host "下载地址: https://github.com/PowerShell/PowerShell/releases" -ForegroundColor Cyan
            return $false
        }
        
        # 版本兼容性警告
        if ($currentVersion -lt $RecommendedVersion) {
            Write-Host "⚠️  PowerShell 版本警告" -ForegroundColor Yellow
            Write-Host "   当前版本: $currentVersion" -ForegroundColor White
            Write-Host "   推荐版本: $RecommendedVersion" -ForegroundColor Green
            Write-Host "   某些功能可能在当前版本下表现不佳，建议升级到 PowerShell 7.x" -ForegroundColor Yellow
            Write-Host ""
        }
        else {
            # Write-Host "✅ PowerShell 版本兼容 ($currentVersion)" -ForegroundColor Green
            # 满足版本不做输出
        }
        
        return $true
    }
    catch {
        Write-Host "❌ 无法检测 PowerShell 版本: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "脚本可能无法正常工作，请检查您的 PowerShell 环境。" -ForegroundColor Yellow
        return $false
    }
}

# 执行版本检测
if (-not (Test-PowerShellCompatibility)) {
    # 版本不兼容，退出脚本执行
    Write-Host "脚本已停止执行。" -ForegroundColor Red
    return
}

# 设置控制台编码为UTF-8以支持中文显示
try {
    [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
    [Console]::InputEncoding = [System.Text.Encoding]::UTF8
    chcp 65001 | Out-Null
}
catch {
    Write-Host "⚠️  编码设置失败，中文显示可能异常: $($_.Exception.Message)" -ForegroundColor Yellow
}

# 统一的提示符配置管理
$global:PromptConfig = @{
    # Git缓存配置
    GitCache     = @{
        Path         = $null   # 当前路径
        Branch       = $null   # 当前分支
        Version      = $null   # 当前版本
        RepoName     = $null   # 仓库名称
        RepoRoot     = $null   # 仓库根目录
        LastUpdated  = $null   # 上次更新时间
        Status       = $null   # Git状态信息
        CommitStatus = $null   # 提交状态
    }
    
    # Git文件监控缓存
    GitFileCache = @{
        HeadFile      = $null
        IndexFile     = $null
        HeadModified  = $null
        IndexModified = $null
    }
    
    # 性能配置
    Performance  = @{
        FastMode             = $false    # 快速模式，跳过详细状态
        CommandTimeout       = 500       # Git命令超时（毫秒）
        EnableFileMonitoring = $true     # 启用文件监控
        GitCacheTimeout      = 10        # Git缓存超时（秒）
    }
    
    # 路径显示配置
    PathDisplay  = @{
        ShowFullPath = $false            # 默认显示目录名，false=目录名，true=绝对路径
        MaxLength    = 60                # 路径最大显示长度
    }
    
    # 时间缓存配置
    TimeCache    = @{
        LastTimeString = ""
        LastTimeUpdate = [DateTime]::MinValue
    }
    
    # 主题配置
    Theme        = @{
        CurrentTheme      = "Classic"
        LastChanged       = (Get-Date)
        ThemeOrder        = @("Classic", "Dark", "Light", "Minimal", "Ocean", "Linux", "Chinese", "ClassicChinese")
        EnableBackgrounds = $true
    }
}

# 配置验证和默认值处理函数
function Initialize-PromptConfig {
    # 验证性能配置
    if ($global:PromptConfig.Performance.GitCacheTimeout -lt 1 -or $global:PromptConfig.Performance.GitCacheTimeout -gt 300) {
        $global:PromptConfig.Performance.GitCacheTimeout = 10
        Write-Warning "Git缓存超时时间无效，已重置为默认值 10 秒"
    }
    
    if ($global:PromptConfig.Performance.CommandTimeout -lt 100 -or $global:PromptConfig.Performance.CommandTimeout -gt 5000) {
        $global:PromptConfig.Performance.CommandTimeout = 500
        Write-Warning "Git命令超时时间无效，已重置为默认值 500 毫秒"
    }
    
    # 验证路径显示配置
    if ($global:PromptConfig.PathDisplay.MaxLength -lt 20 -or $global:PromptConfig.PathDisplay.MaxLength -gt 200) {
        $global:PromptConfig.PathDisplay.MaxLength = 60
        Write-Warning "路径最大长度无效，已重置为默认值 60"
    }
    
    # 确保布尔值类型正确
    $global:PromptConfig.Performance.FastMode = [bool]$global:PromptConfig.Performance.FastMode
    $global:PromptConfig.Performance.EnableFileMonitoring = [bool]$global:PromptConfig.Performance.EnableFileMonitoring
    $global:PromptConfig.PathDisplay.ShowFullPath = [bool]$global:PromptConfig.PathDisplay.ShowFullPath
}

# 初始化配置
Initialize-PromptConfig

# 主题系统 - 全局主题存储
$global:Themes = @{
    "Classic"        = @{
        Name             = "Classic"
        Description      = "经典绿色主题，默认风格（无背景色）"
        Colors           = @{
            Path            = "Green"
            GitRepo         = "Magenta"
            GitBranch       = "Blue"
            GitVersion      = "Red"
            UserHost        = "Yellow"
            Host            = "Blue"
            Time            = "DarkGray"
            StatusAhead     = "Green"
            StatusBehind    = "Red"
            StatusConflict  = "DarkRed"
            StatusStaged    = "Green"
            StatusModified  = "Yellow"
            StatusUntracked = "Cyan"
            Prompt          = "Green"
            NonGitBlock     = "DarkCyan"
            Separator       = "DarkGray"
        }
        BackgroundColors = @{
            PathBlock   = $null
            GitBlock    = $null
            StatusBlock = $null
            TimeBlock   = $null
            UserBlock   = $null
            PromptBlock = $null
        }
        Symbols          = @{
            GitBranch = "🌳"
            Ahead     = "⬆️"
            Behind    = "⬇️"
            Staged    = "📦"
            Modified  = "✏️"
            Untracked = "❓"
            Conflict  = "⚔️"
            Prompt    = "👉"
            NonGit    = "📁"
            Separator = "⬢"
        }
    }
    
    "Dark"           = @{
        Name             = "Dark"
        Description      = "深色主题，适合暗色终端背景，带背景色分区"
        Colors           = @{
            Path            = "White"
            GitRepo         = "White"
            GitBranch       = "Yellow"
            GitVersion      = "Cyan"
            UserHost        = "White"
            Host            = "Gray"
            Time            = "White"
            StatusAhead     = "White"
            StatusBehind    = "White"
            StatusConflict  = "White"
            StatusStaged    = "White"
            StatusModified  = "White"
            StatusUntracked = "White"
            Prompt          = "White"
            NonGitBlock     = "White"
            Separator       = "DarkGray"
        }
        BackgroundColors = @{
            PathBlock   = "DarkBlue"
            GitBlock    = "DarkGreen"
            StatusBlock = "DarkMagenta"
            TimeBlock   = "DarkGray"
            UserBlock   = "DarkCyan"
            PromptBlock = $null
        }
        Symbols          = @{
            GitBranch = "🌙"
            Ahead     = "^"
            Behind    = "v"
            Staged    = "+"
            Modified  = "*"
            Untracked = "?"
            Conflict  = "!"
            Prompt    = "❯"
            NonGit    = "📂"
            Separator = "|"
        }
    }
    
    "Light"          = @{
        Name             = "Light"
        Description      = "浅色主题，适合亮色终端背景，带浅色背景分区"
        Colors           = @{
            Path            = "Black"
            GitRepo         = "DarkBlue"
            GitBranch       = "DarkBlue"
            GitVersion      = "DarkRed"
            UserHost        = "Black"
            Host            = "DarkBlue"
            Time            = "Black"
            StatusAhead     = "DarkGreen"
            StatusBehind    = "DarkRed"
            StatusConflict  = "Red"
            StatusStaged    = "DarkGreen"
            StatusModified  = "DarkYellow"
            StatusUntracked = "DarkCyan"
            Prompt          = "DarkBlue"
            NonGitBlock     = "Black"
            Separator       = "Gray"
        }
        BackgroundColors = @{
            PathBlock   = "Cyan"
            GitBlock    = "Green"
            StatusBlock = "Yellow"
            TimeBlock   = "Gray"
            UserBlock   = "Magenta"
            PromptBlock = $null
        }
        Symbols          = @{
            GitBranch = "☀️"
            Ahead     = "^"
            Behind    = "v"
            Staged    = "+"
            Modified  = "*"
            Untracked = "?"
            Conflict  = "!"
            Prompt    = "▶"
            NonGit    = "📄"
            Separator = "|"
        }
    }
    
    "Minimal"        = @{
        Name             = "Minimal"
        Description      = "极简主题，只显示关键信息（无背景色）"
        Colors           = @{
            Path            = "White"
            GitRepo         = "White"
            GitBranch       = "White"
            GitVersion      = "Gray"
            UserHost        = "White"
            Host            = "White"
            Time            = "DarkGray"
            StatusAhead     = "White"
            StatusBehind    = "White"
            StatusConflict  = "White"
            StatusStaged    = "White"
            StatusModified  = "White"
            StatusUntracked = "White"
            Prompt          = "White"
            NonGitBlock     = "White"
            Separator       = "DarkGray"
        }
        BackgroundColors = @{
            PathBlock   = $null
            GitBlock    = $null
            StatusBlock = $null
            TimeBlock   = $null
            UserBlock   = $null
            PromptBlock = $null
        }
        Symbols          = @{
            GitBranch = "git"
            Ahead     = "+"
            Behind    = "-"
            Staged    = "S"
            Modified  = "M"
            Untracked = "U"
            Conflict  = "C"
            Prompt    = ">"
            NonGit    = ""
            Separator = "|"
        }
    }
    
    "Ocean"          = @{
        Name             = "Ocean"
        Description      = "海洋风格，蓝色系主题，带海洋色彩背景"
        Colors           = @{
            Path            = "White"
            GitRepo         = "White"
            GitBranch       = "Yellow"
            GitVersion      = "Cyan"
            UserHost        = "White"
            Host            = "White"
            Time            = "White"
            StatusAhead     = "White"
            StatusBehind    = "White"
            StatusConflict  = "White"
            StatusStaged    = "White"
            StatusModified  = "White"
            StatusUntracked = "White"
            Prompt          = "Cyan"
            NonGitBlock     = "White"
            Separator       = "DarkBlue"
        }
        BackgroundColors = @{
            PathBlock   = "DarkCyan"
            GitBlock    = "Blue"
            StatusBlock = "DarkBlue"
            TimeBlock   = "DarkCyan"
            UserBlock   = "Blue"
            PromptBlock = $null
        }
        Symbols          = @{
            GitBranch = "🌊"
            Ahead     = "^"
            Behind    = "v"
            Staged    = "+"
            Modified  = "*"
            Untracked = "?"
            Conflict  = "!"
            Prompt    = "🔱"
            NonGit    = "🏠"
            Separator = "|"
        }
    }
    
    "Linux"          = @{
        Name             = "Linux"
        Description      = "Linux终端风格，经典绿色配色，无背景色"
        Colors           = @{
            Path            = "Green"
            GitRepo         = "Green"
            GitBranch       = "Cyan"
            GitVersion      = "Yellow"
            UserHost        = "Green"
            Host            = "Green"
            Time            = "White"
            StatusAhead     = "Green"
            StatusBehind    = "Red"
            StatusConflict  = "Red"
            StatusStaged    = "Green"
            StatusModified  = "Yellow"
            StatusUntracked = "Cyan"
            Prompt          = "Green"
            NonGitBlock     = "Green"
            Separator       = "White"
        }
        BackgroundColors = @{
            # Linux主题保持无背景色，经典终端风格
            PathBlock   = $null
            GitBlock    = $null
            StatusBlock = $null
            TimeBlock   = $null
            UserBlock   = $null
            PromptBlock = $null
        }
        Symbols          = @{
            GitBranch = "±"
            Ahead     = "↑"
            Behind    = "↓"
            Staged    = "●"
            Modified  = "✚"
            Untracked = "…"
            Conflict  = "✖"
            Prompt    = "$"
            NonGit    = "~"
            Separator = ":"
        }
    }
    
    "Chinese"        = @{
        Name             = "Chinese"
        Description      = "中文主题，使用中文描述Git状态"
        Colors           = @{
            Path            = "White"
            GitRepo         = "Cyan"
            GitBranch       = "Cyan"
            GitVersion      = "Gray"
            UserHost        = "Green"
            Host            = "Green"
            Time            = "White"
            StatusAhead     = "Green"
            StatusBehind    = "Red"
            StatusConflict  = "Red"
            StatusStaged    = "Green"
            StatusModified  = "Yellow"
            StatusUntracked = "Blue"
            Prompt          = "Green"
            NonGitBlock     = "Cyan"
            Separator       = "White"
        }
        BackgroundColors = @{
            # 中文主题保持无背景色，简洁风格
            PathBlock   = $null
            GitBlock    = $null
            StatusBlock = $null
            TimeBlock   = $null
            UserBlock   = $null
            PromptBlock = $null
        }
        Symbols          = @{
            GitBranch = "分支"
            Ahead     = "领先"
            Behind    = "落后"
            Staged    = "暂存"
            Modified  = "修改"
            Untracked = "新增"
            Conflict  = "冲突"
            Prompt    = ">"
            NonGit    = "目录"
            Separator = "|"
        }
    }
    
    "ClassicChinese" = @{
        Name             = "ClassicChinese"
        Description      = "经典中文主题，传统绿色配色，中文仓库状态描述"
        Colors           = @{
            Path            = "Green"
            GitRepo         = "Cyan"
            GitBranch       = "Yellow"
            GitVersion      = "Magenta"
            UserHost        = "Green"
            Host            = "Green"
            Time            = "White"
            StatusAhead     = "Green"
            StatusBehind    = "Red"
            StatusConflict  = "Red"
            StatusStaged    = "Green"
            StatusModified  = "Yellow"
            StatusUntracked = "Cyan"
            Prompt          = "Green"
            NonGitBlock     = "Green"
            Separator       = "White"
        }
        BackgroundColors = @{
            PathBlock   = $null
            GitBlock    = $null
            StatusBlock = $null
            TimeBlock   = $null
            UserBlock   = $null
            PromptBlock = $null
        }
        Symbols          = @{
            GitBranch = "🌳"
            Ahead     = "领先"
            Behind    = "落后"
            Staged    = "已暂存"
            Modified  = "已修改"
            Untracked = "未跟踪"
            Conflict  = "有冲突"
            Prompt    = "👉"
            NonGit    = "📁"
            Separator = "|"
        }
    }
}

# 当前主题的颜色和符号（将由主题系统管理）
$global:Colors = @{}
$global:BackgroundColors = @{}
$global:Symbols = @{}

# 优化：简化路径格式化算法
function Format-Path($path, $maxLength = $null) {
    # 使用配置中的最大长度，如果未指定则使用配置默认值
    if ($null -eq $maxLength) {
        $maxLength = $global:PromptConfig.PathDisplay.MaxLength
    }
    
    # 如果配置为显示目录名，则只返回当前目录名
    if (-not $global:PromptConfig.PathDisplay.ShowFullPath) {
        return Split-Path -Leaf $path
    }
    
    # 显示完整路径的逻辑（原有逻辑）
    if ($path.Length -le $maxLength) { return $path }
    
    $segments = $path -split '\\'
    if ($segments.Length -le 3) {
        return ($segments | ForEach-Object { 
                if ($_.Length -gt 15) { $_.Substring(0, 12) + '...' } else { $_ }
            }) -join '\'
    }
    
    return "$($segments[0])\...\$($segments[-2])\$($segments[-1])"
}

# 优化：快速检测是否在Git仓库中
function Test-GitRepository {
    try {
        # 使用更快的检测方法
        $gitDir = git rev-parse --git-dir 2>$null
        return $LASTEXITCODE -eq 0 -and $gitDir
    }
    catch {
        return $false
    }
}

# 优化：检查Git文件是否有变化
function Test-GitFilesChanged([string]$repoRoot) {
    if (!$global:PromptConfig.Performance.EnableFileMonitoring -or !$repoRoot) { return $true }
    
    $headFile = Join-Path $repoRoot ".git\HEAD"
    $indexFile = Join-Path $repoRoot ".git\index"
    
    try {
        $headModified = if (Test-Path $headFile) { (Get-Item $headFile).LastWriteTime } else { $null }
        $indexModified = if (Test-Path $indexFile) { (Get-Item $indexFile).LastWriteTime } else { $null }
        
        $fileCache = $global:PromptConfig.GitFileCache
        $changed = ($fileCache.HeadFile -ne $headFile) -or 
        ($fileCache.IndexFile -ne $indexFile) -or
        ($fileCache.HeadModified -ne $headModified) -or
        ($fileCache.IndexModified -ne $indexModified)
        
        if ($changed) {
            $fileCache.HeadFile = $headFile
            $fileCache.IndexFile = $indexFile
            $fileCache.HeadModified = $headModified
            $fileCache.IndexModified = $indexModified
        }
        
        return $changed
    }
    catch {
        return $true
    }
}

# 合并Git信息获取，减少命令调用次数
function Get-CachedGitInfo([string]$CurrentPath) {
    $gitCache = $global:PromptConfig.GitCache
    $perfConfig = $global:PromptConfig.Performance
    
    # 检查基础缓存
    $cacheValid = ($gitCache.Path -eq $CurrentPath) -and 
    ($gitCache.LastUpdated) -and 
    (((Get-Date) - $gitCache.LastUpdated).TotalSeconds -lt $perfConfig.GitCacheTimeout)
    
    if ($cacheValid -and !$perfConfig.EnableFileMonitoring) {
        return $gitCache
    }
    
    # 快速检测Git仓库
    if (!(Test-GitRepository)) {
        $gitCache.Path = $CurrentPath
        $gitCache.Branch = $null
        $gitCache.RepoName = $null
        $gitCache.RepoRoot = $null
        $gitCache.Version = $null
        $gitCache.Status = $null
        $gitCache.CommitStatus = $null
        $gitCache.LastUpdated = Get-Date
        return $gitCache
    }
    
    # 获取仓库根目录
    $repoRoot = git rev-parse --show-toplevel 2>$null
    if (!$repoRoot) { return $gitCache }
    
    # 检查文件是否有变化
    if ($cacheValid -and $gitCache.RepoRoot -eq $repoRoot -and !(Test-GitFilesChanged $repoRoot)) {
        return $gitCache
    }
    
    # 更新缓存
    $gitCache.Path = $CurrentPath
    $gitCache.RepoRoot = $repoRoot
    $gitCache.LastUpdated = Get-Date
    
    # 优化：使用单个命令获取多个信息
    try {
        # 获取分支信息
        $gitCache.Branch = git rev-parse --abbrev-ref HEAD 2>$null
        
        # 获取仓库名称
        $gitCache.RepoName = if ($repoRoot) { Split-Path -Leaf $repoRoot } else { $null }
        
        # 获取版本信息（如果不在快速模式）
        if (!$perfConfig.FastMode) {
            $gitCache.Version = git describe --tags --always --dirty 2>$null
        }
        
        # 获取状态信息（合并命令）
        if (!$perfConfig.FastMode) {
            $statusOutput = git status --porcelain --branch 2>$null
            if ($statusOutput) {
                # 解析状态
                $branchLine = $statusOutput | Where-Object { $_ -match '^##' } | Select-Object -First 1
                $fileLines = $statusOutput | Where-Object { $_ -notmatch '^##' }
                
                # 提交状态
                $ahead = 0; $behind = 0
                if ($branchLine -match 'ahead (\d+)') { $ahead = [int]$matches[1] }
                if ($branchLine -match 'behind (\d+)') { $behind = [int]$matches[1] }
                $gitCache.CommitStatus = @{ Ahead = $ahead; Behind = $behind }
                
                # 文件状态
                if ($fileLines) {
                    $gitCache.Status = @{
                        Staged    = ($fileLines | Where-Object { $_[0] -match '[AMDRC]' }).Count
                        Modified  = ($fileLines | Where-Object { $_[1] -match '[AMDRC]' }).Count
                        Untracked = ($fileLines -match '^\?\?').Count
                        Conflicts = ($fileLines -match '^DD|AU|UD|UA|DU|AA|UU').Count
                    }
                }
                else {
                    $gitCache.Status = @{ Staged = 0; Modified = 0; Untracked = 0; Conflicts = 0 }
                }
            }
        }
    }
    catch {
        # 静默处理错误，不影响提示符显示
    }
    
    return $gitCache
}

# 优化：缓存时间字符串
function Get-CurrentTime() {
    $timeCache = $global:PromptConfig.TimeCache
    $now = Get-Date
    if (($now - $timeCache.LastTimeUpdate).TotalSeconds -ge 1) {
        $timeCache.LastTimeString = $now.ToString("HH:mm:ss")
        $timeCache.LastTimeUpdate = $now
    }
    return $timeCache.LastTimeString
}

# 背景色支持功能
function Write-HostWithBackground {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Text,
        [string]$ForegroundColor = "White",
        [string]$BackgroundColor = $null,
        [switch]$NoNewline
    )
    
    # 检查是否启用背景色功能
    $useBackground = $global:PromptConfig.Theme.EnableBackgrounds -and 
    $BackgroundColor -and 
    $BackgroundColor -ne $null -and
    (Test-BackgroundColorSupport)
    
    if ($useBackground) {
        Write-Host $Text -ForegroundColor $ForegroundColor -BackgroundColor $BackgroundColor -NoNewline:$NoNewline
    }
    else {
        Write-Host $Text -ForegroundColor $ForegroundColor -NoNewline:$NoNewline
    }
}

function Test-BackgroundColorSupport {
    # 检测终端是否支持背景色
    try {
        return $null -ne $Host.UI.RawUI.BackgroundColor
    }
    catch {
        return $false
    }
}

# 检查终端Unicode支持
function Test-UnicodeSupport {
    try {
        [Console]::OutputEncoding -eq [System.Text.Encoding]::UTF8
    }
    catch {
        $false
    }
}

# 为不支持Unicode的终端创建ASCII符号
function Get-AsciiSymbols($symbols) {
    return @{
        GitBranch = if ($symbols.GitBranch -eq "🌳") { "BR" } elseif ($symbols.GitBranch -eq "🌙") { "DK" } elseif ($symbols.GitBranch -eq "☀️") { "LT" } elseif ($symbols.GitBranch -eq "🌊") { "OC" } else { "git" }
        Ahead     = "^"
        Behind    = "v"
        Staged    = "+"
        Modified  = "*"
        Untracked = "?"
        Conflict  = "!"
        Prompt    = ">"
        NonGit    = "[PC]"
        Separator = "|"
    }
}

# 优化的提示符函数（支持背景色）
$function:prompt = {
    try {
        $path = Get-Location
        $formattedPath = Format-Path $path
        $gitInfo = Get-CachedGitInfo $path
        $time = Get-CurrentTime
        $c = $global:Colors
        $bg = $global:BackgroundColors
        $s = $global:Symbols

        # 清空行
        Write-Host "`r" -NoNewline
        
        if ($gitInfo.Branch) {
            # 检查是否为无背景色主题
            $isCompactTheme = $global:PromptConfig.Theme.CurrentTheme -eq "Classic" -or $global:PromptConfig.Theme.CurrentTheme -eq "Linux" -or $global:PromptConfig.Theme.CurrentTheme -eq "Minimal" -or $global:PromptConfig.Theme.CurrentTheme -eq "Chinese" -or $global:PromptConfig.Theme.CurrentTheme -eq "ClassicChinese"
            
            if ($isCompactTheme) {
                # 经典主题：保持原有紧凑风格
                Write-Host "$formattedPath " -ForegroundColor $c.Path -NoNewline
                Write-Host "$($s.GitBranch) " -ForegroundColor $c.GitRepo -NoNewline
                Write-Host "$($gitInfo.Branch)" -ForegroundColor $c.GitBranch -NoNewline
                
                if ($gitInfo.Version) {
                    Write-Host " $($s.Separator) " -ForegroundColor $c.Separator -NoNewline
                    Write-Host "$($gitInfo.Version)" -ForegroundColor $c.GitVersion -NoNewline
                }
                
                # Git状态显示
                if ($gitInfo.Status -or $gitInfo.CommitStatus) {
                    $statusText = @()
                    
                    if ($gitInfo.CommitStatus) {
                        if ($gitInfo.CommitStatus.Ahead -gt 0) { $statusText += "$($gitInfo.CommitStatus.Ahead)$($s.Ahead)" }
                        if ($gitInfo.CommitStatus.Behind -gt 0) { $statusText += "$($gitInfo.CommitStatus.Behind)$($s.Behind)" }
                    }
                    
                    if ($gitInfo.Status) {
                        if ($gitInfo.Status.Conflicts -gt 0) { $statusText += "$($gitInfo.Status.Conflicts)$($s.Conflict)" }
                        if ($gitInfo.Status.Staged -gt 0) { $statusText += "$($gitInfo.Status.Staged)$($s.Staged)" }
                        if ($gitInfo.Status.Modified -gt 0) { $statusText += "$($gitInfo.Status.Modified)$($s.Modified)" }
                        if ($gitInfo.Status.Untracked -gt 0) { $statusText += "$($gitInfo.Status.Untracked)$($s.Untracked)" }
                    }
                    
                    if ($statusText.Count -gt 0) {
                        Write-Host " $($s.Separator) " -ForegroundColor $c.Separator -NoNewline
                        Write-Host "[" -ForegroundColor $c.Separator -NoNewline
                        
                        for ($i = 0; $i -lt $statusText.Count; $i++) {
                            $item = $statusText[$i]
                            $color = $c.StatusModified
                            
                            if ($item -match [regex]::Escape($s.Ahead) + '$') { $color = $c.StatusAhead }
                            elseif ($item -match [regex]::Escape($s.Behind) + '$') { $color = $c.StatusBehind }
                            elseif ($item -match [regex]::Escape($s.Conflict) + '$') { $color = $c.StatusConflict }
                            elseif ($item -match [regex]::Escape($s.Staged) + '$') { $color = $c.StatusStaged }
                            elseif ($item -match [regex]::Escape($s.Untracked) + '$') { $color = $c.StatusUntracked }
                            
                            Write-Host $item -ForegroundColor $color -NoNewline
                            
                            if ($i -lt $statusText.Count - 1) {
                                Write-Host "  " -ForegroundColor $c.Separator -NoNewline
                            }
                        }
                        
                        Write-Host "]" -ForegroundColor $c.Separator -NoNewline
                    }
                }
            }
            else {
                # 其他主题：使用背景色风格
                Write-HostWithBackground " $formattedPath " -ForegroundColor $c.Path -BackgroundColor $bg.PathBlock -NoNewline
                Write-Host " " -NoNewline
                
                # Git信息显示（带背景）
                Write-HostWithBackground " $($s.GitBranch) $($gitInfo.Branch) " -ForegroundColor $c.GitBranch -BackgroundColor $bg.GitBlock -NoNewline
                
                # 版本信息（如果存在）
                if ($gitInfo.Version) {
                    Write-Host " " -NoNewline
                    Write-HostWithBackground " $($gitInfo.Version) " -ForegroundColor $c.GitVersion -BackgroundColor $bg.GitBlock -NoNewline
                }
                
                # Git状态显示
                if ($gitInfo.Status -or $gitInfo.CommitStatus) {
                    $statusText = @()
                    
                    if ($gitInfo.CommitStatus) {
                        if ($gitInfo.CommitStatus.Ahead -gt 0) { $statusText += "$($gitInfo.CommitStatus.Ahead)$($s.Ahead)" }
                        if ($gitInfo.CommitStatus.Behind -gt 0) { $statusText += "$($gitInfo.CommitStatus.Behind)$($s.Behind)" }
                    }
                    
                    if ($gitInfo.Status) {
                        if ($gitInfo.Status.Conflicts -gt 0) { $statusText += "$($gitInfo.Status.Conflicts)$($s.Conflict)" }
                        if ($gitInfo.Status.Staged -gt 0) { $statusText += "$($gitInfo.Status.Staged)$($s.Staged)" }
                        if ($gitInfo.Status.Modified -gt 0) { $statusText += "$($gitInfo.Status.Modified)$($s.Modified)" }
                        if ($gitInfo.Status.Untracked -gt 0) { $statusText += "$($gitInfo.Status.Untracked)$($s.Untracked)" }
                    }
                    
                    if ($statusText.Count -gt 0) {
                        Write-Host " " -NoNewline
                        Write-HostWithBackground " $($statusText -join ' ') " -ForegroundColor $c.StatusStaged -BackgroundColor $bg.StatusBlock -NoNewline
                    }
                }
            }
        }
        else {
            # 非Git目录显示
            if ($global:PromptConfig.Theme.CurrentTheme -eq "Classic" -or $global:PromptConfig.Theme.CurrentTheme -eq "Linux" -or $global:PromptConfig.Theme.CurrentTheme -eq "Minimal" -or $global:PromptConfig.Theme.CurrentTheme -eq "Chinese" -or $global:PromptConfig.Theme.CurrentTheme -eq "ClassicChinese") {
                # 紧凑主题：保持原有风格
                Write-Host "$formattedPath " -ForegroundColor $c.Path -NoNewline
                Write-Host "$($s.NonGit) " -ForegroundColor $c.NonGitBlock -NoNewline
                Write-Host "$env:USERNAME@$env:COMPUTERNAME" -ForegroundColor $c.UserHost -NoNewline
            }
            else {
                # 其他主题：使用背景色
                Write-HostWithBackground " $formattedPath " -ForegroundColor $c.Path -BackgroundColor $bg.PathBlock -NoNewline
                Write-Host " " -NoNewline
                Write-HostWithBackground " $($s.NonGit) $env:USERNAME@$env:COMPUTERNAME " -ForegroundColor $c.UserHost -BackgroundColor $bg.UserBlock -NoNewline
            }
        }
        
        # 时间显示
        $availableWidth = $Host.UI.RawUI.BufferSize.Width
        $currentLength = [Console]::CursorLeft
        $timeDisplay = if ($global:PromptConfig.Theme.CurrentTheme -eq "Classic" -or $global:PromptConfig.Theme.CurrentTheme -eq "Linux" -or $global:PromptConfig.Theme.CurrentTheme -eq "ClassicChinese") { "[$time]" } else { " [$time] " }
        $spacesNeeded = [Math]::Max(2, $availableWidth - $currentLength - $timeDisplay.Length)
        
        Write-Host (" " * $spacesNeeded) -NoNewline
        
        if ($global:PromptConfig.Theme.CurrentTheme -eq "Classic" -or $global:PromptConfig.Theme.CurrentTheme -eq "Linux" -or $global:PromptConfig.Theme.CurrentTheme -eq "ClassicChinese") {
            Write-Host $timeDisplay -ForegroundColor $c.Time -NoNewline
        }
        else {
            Write-HostWithBackground $timeDisplay -ForegroundColor $c.Time -BackgroundColor $bg.TimeBlock -NoNewline
        }

        # 命令提示符
        Write-Host "`n$($s.Prompt) " -ForegroundColor $c.Prompt -NoNewline
        return " "
        
    }
    catch {
        # 降级处理：出错时显示简单提示符
        Write-Host "[ERROR: $($_.Exception.Message)] " -ForegroundColor Red -NoNewline
        Write-Host "PS $((Get-Location).Path)> " -ForegroundColor Green -NoNewline
        return " "
    }
}

# 性能调优函数 - 用户可调用的配置函数

# 启用快速模式 - 跳过详细的Git状态检查，提升响应速度
# 适用场景：大型仓库或网络较慢时使用
function Enable-FastMode { 
    $global:PromptConfig.Performance.FastMode = $true 
    Write-Host "已启用快速模式 - 跳过详细Git状态检查" -ForegroundColor Yellow
}

# 禁用快速模式 - 显示完整的Git状态信息
# 适用场景：需要查看详细Git状态时使用
function Disable-FastMode { 
    $global:PromptConfig.Performance.FastMode = $false 
    Write-Host "已禁用快速模式 - 显示完整Git状态信息" -ForegroundColor Yellow
}

# 设置Git缓存超时时间 - 自定义缓存有效期
# 参数：$seconds - 缓存超时秒数（建议5-30秒）
# 较短时间：信息更及时，但性能稍差
# 较长时间：性能更好，但信息可能滞后
function Set-GitCacheTimeout([int]$seconds) { 
    if ($seconds -lt 1 -or $seconds -gt 300) {
        Write-Host "缓存超时时间应在1-300秒之间" -ForegroundColor Red
        return
    }
    $global:PromptConfig.Performance.GitCacheTimeout = $seconds
    Write-Host "Git缓存超时已设置为 $seconds 秒" -ForegroundColor Yellow
}

# 路径显示控制函数

# 切换路径显示模式 - 在目录名和完整路径之间切换
# 无参数调用，自动在两种模式间切换
function Switch-PathDisplay {
    $global:PromptConfig.PathDisplay.ShowFullPath = -not $global:PromptConfig.PathDisplay.ShowFullPath
    $mode = if ($global:PromptConfig.PathDisplay.ShowFullPath) { "完整路径" } else { "目录名" }
    Write-Host "已切换到 $mode 显示模式" -ForegroundColor Cyan
}

# 配置管理函数

# 获取完整配置信息
function Get-PromptConfig {
    return $global:PromptConfig | ConvertTo-Json -Depth 3
}

# 重置配置为默认值
function Reset-PromptConfig {
    Initialize-PromptConfig
    Write-Host "提示符配置已重置为默认值" -ForegroundColor Green
}

# 设置路径最大显示长度
function Set-PathMaxLength([int]$length) {
    if ($length -lt 20 -or $length -gt 200) {
        Write-Host "路径最大长度应在20-200之间" -ForegroundColor Red
        return
    }
    $global:PromptConfig.PathDisplay.MaxLength = $length
    Write-Host "路径最大显示长度已设置为 $length" -ForegroundColor Yellow
}

# ==================== 主题系统核心函数 ====================

# 1. Set-PromptTheme - 切换主题
function Set-PromptTheme {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ArgumentCompleter({
                param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
                $global:Themes.Keys | Where-Object { $_ -like "$wordToComplete*" }
            })]
        [string]$ThemeName,
        
        [Parameter(Mandatory = $false)]
        [switch]$Silent
    )
    
    # 验证主题是否存在
    if (-not $global:Themes.ContainsKey($ThemeName)) {
        $availableThemes = $global:Themes.Keys -join ", "
        Write-Host "主题 '$ThemeName' 不存在。可用主题: $availableThemes" -ForegroundColor Red
        return
    }
    
    try {
        # 获取主题配置
        $theme = $global:Themes[$ThemeName]
        
        # 应用主题（包括背景色）
        $global:Colors = $theme.Colors.Clone()
        $global:BackgroundColors = if ($theme.BackgroundColors) { 
            $theme.BackgroundColors.Clone() 
        }
        else { 
            @{} # 如果主题没有背景色配置，使用空哈希表
        }
        $global:Symbols = $theme.Symbols.Clone()
        
        # 如果不支持Unicode，使用ASCII符号
        if (!(Test-UnicodeSupport)) {
            $global:Symbols = Get-AsciiSymbols $global:Symbols
        }
        
        # 更新配置
        $global:PromptConfig.Theme.CurrentTheme = $ThemeName
        $global:PromptConfig.Theme.LastChanged = Get-Date
        
        # 用户反馈
        if (-not $Silent) {
            Write-Host "✓ 已切换到 '$ThemeName' 主题" -ForegroundColor Green
            Write-Host "  $($theme.Description)" -ForegroundColor Gray
        }
        
        # 保存配置到文件
        Save-ThemeConfig
        
    }
    catch {
        Write-Host "切换主题时发生错误: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "已恢复到默认主题" -ForegroundColor Yellow
        Set-PromptTheme "Classic"
    }
}

# 2. Get-PromptThemes - 列出所有主题
function Get-PromptThemes {
    [CmdletBinding()]
    param()
    
    $currentTheme = $global:PromptConfig.Theme.CurrentTheme
    
    Write-Host "`n可用主题:" -ForegroundColor Cyan
    Write-Host ("=" * 50) -ForegroundColor DarkGray
    
    foreach ($themeName in $global:Themes.Keys | Sort-Object) {
        $theme = $global:Themes[$themeName]
        $isCurrent = $themeName -eq $currentTheme
        
        # 当前主题标记
        $marker = if ($isCurrent) { "● " } else { "  " }
        $nameColor = if ($isCurrent) { "Green" } else { "White" }
        
        Write-Host $marker -NoNewline -ForegroundColor Green
        Write-Host $themeName -NoNewline -ForegroundColor $nameColor
        Write-Host " - " -NoNewline -ForegroundColor DarkGray
        Write-Host $theme.Description -ForegroundColor Gray
        
        # 显示主题预览（颜色示例）
        if ($isCurrent) {
            Write-Host "    预览: " -NoNewline -ForegroundColor DarkGray
            Write-Host "路径" -NoNewline -ForegroundColor $theme.Colors.Path
            Write-Host " " -NoNewline
            Write-Host "$($theme.Symbols.GitBranch)分支" -NoNewline -ForegroundColor $theme.Colors.GitBranch
            Write-Host " " -NoNewline
            Write-Host "$($theme.Symbols.Staged)1" -NoNewline -ForegroundColor $theme.Colors.StatusStaged
            Write-Host " " -NoNewline
            Write-Host "$($theme.Symbols.Modified)2" -ForegroundColor $theme.Colors.StatusModified
        }
    }
    
    Write-Host "`n使用方法: Set-PromptTheme <主题名>" -ForegroundColor Yellow
    Write-Host "当前主题: $currentTheme" -ForegroundColor Cyan
}

# 3. Get-CurrentTheme - 获取当前主题
function Get-CurrentTheme {
    [CmdletBinding()]
    param()
    
    $currentThemeName = $global:PromptConfig.Theme.CurrentTheme
    $currentTheme = $global:Themes[$currentThemeName]
    $lastChanged = $global:PromptConfig.Theme.LastChanged
    
    Write-Host "当前主题信息:" -ForegroundColor Cyan
    Write-Host ("=" * 30) -ForegroundColor DarkGray
    Write-Host "名称: " -NoNewline -ForegroundColor Gray
    Write-Host $currentThemeName -ForegroundColor Green
    Write-Host "描述: " -NoNewline -ForegroundColor Gray
    Write-Host $currentTheme.Description -ForegroundColor White
    Write-Host "切换时间: " -NoNewline -ForegroundColor Gray
    Write-Host $lastChanged.ToString("yyyy-MM-dd HH:mm:ss") -ForegroundColor White
    
    # 显示主题预览
    Write-Host "`n主题预览:" -ForegroundColor Cyan
    Write-Host "路径示例: " -NoNewline -ForegroundColor Gray
    Write-Host "C:\Projects\MyRepo" -ForegroundColor $currentTheme.Colors.Path
    Write-Host "Git示例: " -NoNewline -ForegroundColor Gray
    Write-Host "$($currentTheme.Symbols.GitBranch) " -NoNewline -ForegroundColor $currentTheme.Colors.GitRepo
    Write-Host "main " -NoNewline -ForegroundColor $currentTheme.Colors.GitBranch
    Write-Host "[$($currentTheme.Symbols.Staged)2, $($currentTheme.Symbols.Modified)1]" -ForegroundColor $currentTheme.Colors.StatusStaged
    
    return @{
        Name        = $currentThemeName
        Description = $currentTheme.Description
        LastChanged = $lastChanged
    }
}

# 4. Switch-PromptTheme - 循环切换主题
function Switch-PromptTheme {
    [CmdletBinding()]
    param()
    
    try {
        $currentTheme = $global:PromptConfig.Theme.CurrentTheme
        $themeOrder = $global:PromptConfig.Theme.ThemeOrder
        
        # 找到当前主题在顺序中的位置
        $currentIndex = $themeOrder.IndexOf($currentTheme)
        
        # 如果当前主题不在顺序中，从第一个开始
        if ($currentIndex -eq -1) {
            $nextIndex = 0
        }
        else {
            # 切换到下一个主题，如果是最后一个则回到第一个
            $nextIndex = ($currentIndex + 1) % $themeOrder.Count
        }
        
        $nextTheme = $themeOrder[$nextIndex]
        
        # 切换到下一个主题
        Set-PromptTheme $nextTheme
        
        # 显示切换信息
        Write-Host "🔄 " -NoNewline -ForegroundColor Cyan
        Write-Host "循环切换 " -NoNewline -ForegroundColor Gray
        Write-Host "($($currentIndex + 1)/$($themeOrder.Count) → $($nextIndex + 1)/$($themeOrder.Count))" -ForegroundColor DarkGray
        
    }
    catch {
        Write-Host "循环切换主题时发生错误: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "尝试切换到默认主题" -ForegroundColor Yellow
        Set-PromptTheme "Classic"
    }
}

# ==================== 背景色控制函数 ====================

function Enable-ThemeBackgrounds {
    [CmdletBinding()]
    param()
    
    $global:PromptConfig.Theme.EnableBackgrounds = $true
    Write-Host "✓ 已启用主题背景色" -ForegroundColor Green
    Write-Host "  背景色将在支持的主题中显示" -ForegroundColor Gray
    Save-ThemeConfig
}

function Disable-ThemeBackgrounds {
    [CmdletBinding()]
    param()
    
    $global:PromptConfig.Theme.EnableBackgrounds = $false
    Write-Host "✓ 已禁用主题背景色" -ForegroundColor Yellow
    Write-Host "  所有主题将使用纯文本显示" -ForegroundColor Gray
    Save-ThemeConfig
}

function Switch-ThemeBackgrounds {
    [CmdletBinding()]
    param()
    
    if ($global:PromptConfig.Theme.EnableBackgrounds) {
        Disable-ThemeBackgrounds
    }
    else {
        Enable-ThemeBackgrounds
    }
}

function Get-BackgroundStatus {
    [CmdletBinding()]
    param()
    
    $status = if ($global:PromptConfig.Theme.EnableBackgrounds) { "启用" } else { "禁用" }
    $support = if (Test-BackgroundColorSupport) { "支持" } else { "不支持" }
    
    Write-Host "背景色状态:" -ForegroundColor Cyan
    Write-Host "  功能状态: $status" -ForegroundColor White
    Write-Host "  终端支持: $support" -ForegroundColor White
    
    if ($global:PromptConfig.Theme.EnableBackgrounds -and -not (Test-BackgroundColorSupport)) {
        Write-Host "  ⚠️  当前终端可能不完全支持背景色显示" -ForegroundColor Yellow
    }
}

# ==================== 主题配置持久化 ====================

function Save-ThemeConfig {
    try {
        $configPath = Join-Path $env:USERPROFILE ".prompt-theme-config.json"
        $config = @{
            CurrentTheme      = $global:PromptConfig.Theme.CurrentTheme
            LastChanged       = $global:PromptConfig.Theme.LastChanged
            EnableBackgrounds = $global:PromptConfig.Theme.EnableBackgrounds
        }
        $config | ConvertTo-Json | Set-Content -Path $configPath -Encoding UTF8
    }
    catch {
        Write-Host "保存主题配置时发生错误: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "主题配置将不会持久化保存" -ForegroundColor Yellow
    }
}

function Import-ThemeConfig {
    try {
        $configPath = Join-Path $env:USERPROFILE ".prompt-theme-config.json"
        if (Test-Path $configPath) {
            $config = Get-Content -Path $configPath -Encoding UTF8 | ConvertFrom-Json
            if ($global:Themes.ContainsKey($config.CurrentTheme)) {
                # 恢复背景色设置
                if ($config.PSObject.Properties.Name -contains "EnableBackgrounds") {
                    $global:PromptConfig.Theme.EnableBackgrounds = $config.EnableBackgrounds
                }
                Set-PromptTheme $config.CurrentTheme -Silent
            }
        }
    }
    catch {
        Write-Host "加载主题配置时发生错误: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "正在恢复到默认主题..." -ForegroundColor Yellow
        
        # 恢复到默认主题
        try {
            Set-PromptTheme "Classic"
            Write-Host "已恢复到Classic默认主题" -ForegroundColor Green
        }
        catch {
            Write-Host "恢复默认主题失败，请手动执行: Set-PromptTheme 'Classic'" -ForegroundColor Red
        }
    }
}

# ==================== 主题系统初始化 ====================

function Initialize-ThemeSystem {
    # 确保主题配置存在
    if (-not $global:PromptConfig.Theme) {
        $global:PromptConfig.Theme = @{
            CurrentTheme      = "Classic"
            LastChanged       = (Get-Date)
            ThemeOrder        = @("Classic", "Dark", "Light", "Minimal", "Ocean", "Linux", "Chinese", "ClassicChinese")
            EnableBackgrounds = $true
        }
    }
    
    # 确保背景色配置存在
    if (-not ($global:PromptConfig.Theme.PSObject.Properties.Name -contains "EnableBackgrounds")) {
        $global:PromptConfig.Theme.EnableBackgrounds = $true
    }
    
    # 加载保存的主题配置
    Import-ThemeConfig
    
    # 如果没有加载到有效主题，使用默认主题
    if (-not $global:Colors -or $global:Colors.Count -eq 0 -or -not $global:Symbols -or $global:Symbols.Count -eq 0) {
        Set-PromptTheme "Classic" -Silent
    }

    # 确保背景色变量存在
    if (-not $global:BackgroundColors) {
        $global:BackgroundColors = @{}
    }
}

# 初始化主题系统
Initialize-ThemeSystem

# ============================================================================
# 统一控制函数 - 替代所有分散的控制函数
# ============================================================================

function Invoke-PromptControl {
    [CmdletBinding()]
    param(
        [Parameter(Position = 0)]
        [ValidateSet("t", "theme", "bg", "background", "perf", "performance", "path", "cfg", "config", "help", "?")]
        [string]$Category,
        
        [Parameter(Position = 1)]
        [string]$Action,
        
        [Parameter(Position = 2)]
        [string]$Value
    )
    
    # 如果没有参数，显示帮助
    if (-not $Category) {
        Show-PromptHelp
        return
    }
    
    switch ($Category) {
        { $_ -in @("t", "theme") } {
            switch ($Action) {
                "set" {
                    if (-not $Value) {
                        Write-Host "请指定主题名称。可用主题: $((Get-PromptThemes) -join ', ')" -ForegroundColor Yellow
                        return
                    }
                    Set-PromptTheme $Value
                }
                "ls" {
                    Get-PromptThemes
                }
                "+" {
                    Switch-PromptTheme
                }
                default {
                    if ($Action -and $global:Themes.ContainsKey($Action)) {
                        # 直接指定主题名
                        Set-PromptTheme $Action
                    }
                    else {
                        # 无参数或无效参数，显示当前主题
                        Get-CurrentTheme
                    }
                }
            }
        }
        
        { $_ -in @("bg", "background") } {
            switch ($Action) {
                "on" {
                    Enable-ThemeBackgrounds
                }
                "off" {
                    Disable-ThemeBackgrounds
                }
                "?" {
                    Get-BackgroundStatus
                }
                default {
                    # 无参数，切换背景色状态
                    Switch-ThemeBackgrounds
                }
            }
        }
        
        { $_ -in @("perf", "performance") } {
            switch ($Action) {
                "fast" {
                    if ($global:PromptConfig.Performance.FastMode) {
                        Disable-FastMode
                    }
                    else {
                        Enable-FastMode
                    }
                }
                "cache" {
                    if ($Value -and $Value -match '^\d+$') {
                        Set-GitCacheTimeout ([int]$Value)
                    }
                    else {
                        Write-Host "请指定缓存超时秒数 (1-300)，例如: mp perf cache 10" -ForegroundColor Yellow
                    }
                }
                default {
                    Write-Host "性能选项:" -ForegroundColor Cyan
                    Write-Host "  mp perf fast     - 切换快速模式" -ForegroundColor White
                    Write-Host "  mp perf cache N  - 设置缓存超时(秒)" -ForegroundColor White
                    Write-Host "当前状态:" -ForegroundColor Cyan
                    Write-Host "  快速模式: $($global:PromptConfig.Performance.FastMode)" -ForegroundColor White
                    Write-Host "  缓存超时: $($global:PromptConfig.Performance.GitCacheTimeout)秒" -ForegroundColor White
                }
            }
        }
        
        "path" {
            if ($Action -and $Action -match '^\d+$') {
                # 设置路径长度
                Set-PathMaxLength ([int]$Action)
            }
            else {
                # 切换路径显示模式
                Switch-PathDisplay
            }
        }
        
        { $_ -in @("cfg", "config") } {
            switch ($Action) {
                "save" {
                    Save-ThemeConfig
                    Write-Host "配置已保存" -ForegroundColor Green
                }
                "load" {
                    Import-ThemeConfig
                    Write-Host "配置已加载" -ForegroundColor Green
                }
                "show" {
                    Get-PromptConfig
                }
                "reset" {
                    Reset-PromptConfig
                }
                default {
                    Write-Host "配置选项:" -ForegroundColor Cyan
                    Write-Host "  mp cfg save   - 保存当前配置" -ForegroundColor White
                    Write-Host "  mp cfg load   - 加载保存的配置" -ForegroundColor White
                    Write-Host "  mp cfg show   - 显示完整配置" -ForegroundColor White
                    Write-Host "  mp cfg reset  - 重置为默认配置" -ForegroundColor White
                }
            }
        }
        
        { $_ -in @("help", "?") } {
            Show-PromptHelp
        }
        
        default {
            Write-Host "未知类别: $Category" -ForegroundColor Red
            Show-PromptHelp
        }
    }
}

function Show-PromptHelp {
    Write-Host "`n=== PowerShell 提示符控制命令 ===" -ForegroundColor Cyan
    Write-Host "`n主题管理:" -ForegroundColor Yellow
    Write-Host "  mp t              - 显示当前主题" -ForegroundColor White
    Write-Host "  mp t ls           - 列出所有主题" -ForegroundColor White
    Write-Host "  mp t set <name>   - 设置指定主题" -ForegroundColor White
    Write-Host "  mp t <name>       - 直接设置主题" -ForegroundColor White
    Write-Host "  mp t +            - 切换到下一个主题" -ForegroundColor White
    
    Write-Host "`n背景色管理:" -ForegroundColor Yellow
    Write-Host "  mp bg             - 切换背景色开关" -ForegroundColor White
    Write-Host "  mp bg on          - 启用背景色" -ForegroundColor White
    Write-Host "  mp bg off         - 禁用背景色" -ForegroundColor White
    Write-Host "  mp bg ?           - 查看背景色状态" -ForegroundColor White
    
    Write-Host "`n性能管理:" -ForegroundColor Yellow
    Write-Host "  mp perf           - 显示性能状态" -ForegroundColor White
    Write-Host "  mp perf fast      - 切换快速模式" -ForegroundColor White
    Write-Host "  mp perf cache <N> - 设置缓存超时(秒)" -ForegroundColor White
    
    Write-Host "`n路径显示:" -ForegroundColor Yellow
    Write-Host "  mp path           - 切换路径显示模式" -ForegroundColor White
    Write-Host "  mp path <N>       - 设置路径最大长度" -ForegroundColor White
    
    Write-Host "`n配置管理:" -ForegroundColor Yellow
    Write-Host "  mp cfg            - 显示配置选项" -ForegroundColor White
    Write-Host "  mp cfg save       - 保存当前配置" -ForegroundColor White
    Write-Host "  mp cfg load       - 加载保存的配置" -ForegroundColor White
    Write-Host "  mp cfg show       - 显示完整配置" -ForegroundColor White
    Write-Host "  mp cfg reset      - 重置为默认配置" -ForegroundColor White
    
    Write-Host "`n帮助:" -ForegroundColor Yellow
    Write-Host "  mp help           - 显示此帮助信息" -ForegroundColor White
    Write-Host "  mp ?              - 显示此帮助信息" -ForegroundColor White
    Write-Host ""
}

# 创建简短别名
try {
    Set-Alias -Name "Manage-Prompt" -Value "Invoke-PromptControl" -Scope Global -Force
}
catch {
    Write-Host "警告: 无法创建 Manage-Prompt 别名" -ForegroundColor Yellow
}

try {
    Set-Alias -Name "mp" -Value "Invoke-PromptControl" -Scope Global -Force
}
catch {
    Write-Host "警告: 无法创建 mp 别名，可能已存在只读别名。请使用 Invoke-PromptControl 或 Manage-Prompt" -ForegroundColor Yellow
}